package com.wolfking.jeesite.listener;

import com.google.gson.Gson;
import com.wolfking.jeesite.entity.SignEvent;
import com.wolfking.jeesite.event.AbstractSignEvent;
import com.wolfking.jeesite.event.DefaultEvent;
import com.wolfking.jeesite.mapper.SignEventMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

public abstract class AbstractSignEventListener<T extends AbstractSignEvent> implements ApplicationListener<T> {


    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected SignEventMapper signEventMapper;


    @Override
    public void onApplicationEvent(T event) {
        if (event instanceof DefaultEvent) {
            logger.debug("{} event ,user id is {}", event.getClass(), event.getUserId());
            logDebugJson(event);
        } else {
            logger.info("{} event ,user id is {}", event.getClass(), event.getUserId());
            logInfoJson(event);
        }
        saveSysSignEvent(event);
    }

    protected void logInfoJson(T event) {
        if (logger.isInfoEnabled()) {
            logger.info("sign event is {}", new Gson().toJson(event));
        }
    }

    protected void logDebugJson(T event) {
        if (logger.isDebugEnabled()) {
            logger.debug("sign event is {}", new Gson().toJson(event));
        }
    }

    protected void saveSysSignEvent(T event) {
        try {
            signEventMapper.insert(event.convert2SignEvent());
        } catch (Exception e) {
            logger.warn("", e);
        }
    }

    protected void saveSysSignEvent(SignEvent event) {
        try {
            signEventMapper.insert(event);
        } catch (Exception e) {
            logger.warn("", e);
        }
    }
}
